package com.example.test;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.Image;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class MainActivity extends AppCompatActivity {
    String url = null;
    private ImageButton imagebutton;
    private TextView textView;
    private String location;
    private TextView nowText;

    private TextView firstweather;
    private TextView secondweather;
    private TextView thridweather;
    private TextView fourthweather;
    private TextView[] textViews = new TextView[5];

    private TextView firstdate;
    private TextView seconddate;
    private TextView thriddate;
    private TextView fourthdate;
    private TextView[] date = new TextView[5];

    private ImageView image;
    private ImageView secondimage;
    private ImageView thridimage;
    private ImageView fourthimage;
    private ImageView firstimage;
    private ImageView[] imageViews = new ImageView[5];
    private static final String TAG = "MainActivity";

    //定义广播接收器
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //判断接收到的intent是否是我们想要的，通过判断action是否是“com.weather.refresh”，如果是，打印输出“refresh”，并且再次请求天气情况。
            if(action.equals("com.weather.refresh")){
             //   Toast.makeText(getApplication(),"refresh",Toast.LENGTH_LONG).show();

                new MyAsyncTask(url).execute();
                Log.d(TAG,"boardcast received!");
               // Getweather getweather = new Getweather();
               // getweather.execute(url, defaultName);
            }
        }
    };

    // 实现onDestroy()方法，在Activity结束时结束服务，并注销接受者：
    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(new Intent(this, RefreshService.class));
        unregisterReceiver(broadcastReceiver);
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //注册接收器
        IntentFilter inf = new IntentFilter();
        inf.addAction("com.weather.refresh");
        registerReceiver(broadcastReceiver, inf);
        //开启服务
        startService(new Intent(this, RefreshService.class));

        //点击跳转去下一个页面
        imagebutton = (ImageButton) findViewById(R.id.city_button);
        imagebutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, CityActivity.class);
                startActivityForResult(intent,1);
            }
        });

        textView = (TextView) findViewById(R.id.info_left_text);
        firstweather = (TextView) findViewById(R.id.first_weather);
        secondweather = (TextView) findViewById(R.id.second_weather);
        thridweather = (TextView) findViewById(R.id.third_weather);
        fourthweather = (TextView) findViewById(R.id.fourth_weather);

        textViews[0] = textView;
        textViews[1] = firstweather;
        textViews[2] = secondweather;
        textViews[3] = thridweather;
        textViews[4] = fourthweather;

        firstdate = (TextView) findViewById(R.id.first_date);
        seconddate = (TextView) findViewById(R.id.second_date);
        thriddate = (TextView) findViewById(R.id.third_date);
        fourthdate = (TextView) findViewById(R.id.fourth_date);
        date[1] = firstdate;
        date[2] = seconddate;
        date[3] = thriddate;
        date[4] = fourthdate;

        image = (ImageView) findViewById(R.id.now_img);
        firstimage = (ImageView) findViewById(R.id.first_img);
        secondimage = (ImageView) findViewById(R.id.second_img);
        thridimage = (ImageView) findViewById(R.id.third_img);
        fourthimage = (ImageView) findViewById(R.id.fourth_img);

        imageViews[0] = image;
        imageViews[1] = firstimage;
        imageViews[2] = secondimage;
        imageViews[3] = thridimage;
        imageViews[4] = fourthimage;

        nowText = (TextView) findViewById(R.id.now_text);


        Intent intent = getIntent();
        location = intent.getStringExtra("location");
        if (location == null) {
            location = "北京 朝阳";
        }

        String [] arr = location.split("\\s+");
        // arr[1]就是url中需要的地址
        int size = arr.length;
        url = "http://api.jisuapi.com/weather/query?appkey=88a8f480061791e6&city="+arr[size-1];
        new MyAsyncTask(url).execute();

//        onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 1 && resultCode == Activity.RESULT_OK){
            Bundle bundle = data.getExtras();
            String cityname = bundle.getString("cityname");
            String[] params = cityname.split("\b");
//            defaultName = params[params.length - 1];
            // arr[1]就是url中需要的地址
            int size1 = params.length;
            url = "http://api.jisuapi.com/weather/query?appkey=88a8f480061791e6&city="+params[size1-1];
            location = params[size1 - 1];
            new MyAsyncTask(url).execute();
        }
    }

    class MyAsyncTask extends AsyncTask<String,Void,CityBean>{
        String mUrl;
        public MyAsyncTask(String url)
        {
            this.mUrl = url;
        }

        @Override
        // doInBackground
        protected CityBean doInBackground(String... params) {

            Log.d("url",mUrl);
            //连接、解析、返回一个json对象
            try {
                URL url = new URL(mUrl);
                URLConnection urlConnection = url.openConnection() ;
                InputStream inputStream = urlConnection.getInputStream();
                StringBuilder builder = new StringBuilder();
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"utf8");
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String line = null;
                while ((line = bufferedReader.readLine())!=null)
                {
                    builder.append(System.getProperty("line.separator"));
                    builder.append(line);
                }
                String json = builder.toString();
                Log.d("json",json);

                return new Gson().fromJson(json, CityBean.class);

            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(CityBean cityBean) {

            nowText.setText(cityBean.result.date);
            getWeather(cityBean,textViews,date,imageViews);

        }
    }

    public void getWeather(CityBean cityBean,TextView[] textViews, TextView[] date, ImageView[] imageViews)
    {
        //当天的天气
        String week = cityBean.result.daily.get(0).week;
        String weather = cityBean.result.daily.get(0).day.weather;
        textViews[0].setText(location + "\n\n"+week + "\n\n"+weather);
        if(weather.equals("晴"))
        {
            image.setImageResource(R.drawable.sun);
        }else if(weather.equals("阴")|| weather.equals("多云"))
        {
            image.setImageResource(R.drawable.cloudy);
        }else
//            if(weather.matches(".*雨.*"))
        {
            image.setImageResource(R.drawable.rainy);
        }


        //预测四天的天气
        for (int i=1;i<5;i++)
        {
            String aweek = cityBean.result.daily.get(i).week;
            String aweather = cityBean.result.daily.get(i).day.weather;
            textViews[i].setText(aweather);
            date[i].setText(aweek);
            if(aweather.equals("晴"))
            {
                imageViews[i].setImageResource(R.drawable.sun);

            }else if(aweather.equals("阴")|| aweather.equals("多云"))
            {
                imageViews[i].setImageResource(R.drawable.cloudy);

            }else
//                if(aweather.matches(".*雨.*"))
            {
                imageViews[i].setImageResource(R.drawable.rainy);
            }
        }

    }

}
